package com.atguigui.leetcode;

/**
 * 1022.从根到叶的二进制数之和
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/5/30 23:02
 */
public class P1022SumOfRootToLeafBinaryNumbers {
    public static void main(String[] args) {
        Solution solution = new P1022SumOfRootToLeafBinaryNumbers().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    // Definition for a binary tree node.
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public int sumRootToLeaf(TreeNode root) {
            return dfs(root, 0);
        }

        public int dfs(TreeNode root, int val) {

            if (root == null) {
                return 0;
            }

            // 一个为真即为真
            // 类似于位数0和1的拼接
            val = (val << 1) | root.val;
            if (root.left == null && root.right == null) {
                // 返回这个拼接数
                return val;
            }

            // 返回left + right的值，然后一次递归每个根节点
            return dfs(root.left, val) + dfs(root.right, val);
        }

    }
}
